package com.rockcent.api.controller;

import com.rockcent.api.Routes;
import com.rockcent.api.helper.UserHelper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.utils.BigDecimalUtils;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.helper.SysMessageHelper;
import com.rockcent.mall.lib.constants.SysMessageConstants;
import com.rockcent.mall.lib.domain.Mall;
import com.rockcent.mall.lib.domain.Merchant;
import com.rockcent.mall.lib.domain.MerchantRechargeFlow;
import com.rockcent.mall.lib.domain.SysMessage;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.dto.MerchantRechargeFlowDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.repository.MerchantRechargeFlowRepository;
import com.rockcent.service.MallSrv;
import com.rockcent.service.MerchantRechargeFlowSrv;
import com.rockcent.service.MerchantRechargeSrv;
import com.rockcent.service.MerchantSrv;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Date;

import static com.rockcent.common.utils.DateFormatUtils.DATE_FORMAT2;

/**
 * Created by DK on 17/3/28.
 */
@RestController
@RequestMapping(value = Routes.API_VERSION)
public class MerchantRechargeController extends BaseController {


    private final Logger log = LoggerFactory.getLogger(MerchantRechargeController.class);

    @Autowired
    private UserHelper userHelper;

    @Autowired
    private MerchantRechargeSrv merchantRechargeSrv;

    @Autowired
    private MerchantSrv merchantSrv;

    @Autowired
    private MerchantRechargeFlowRepository merchantRechargeFlowRepository;


    @Autowired
    private MerchantRechargeFlowSrv merchantRechargeFlowSrv;


    @Autowired
    private MallSrv mallSrv;


    /**
     * @api {get} /v1/merchant/recharge/page B 充值记录分页
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} rechargeStatus <code>必选参数</code> 充值状态 ：ALL("全部"), WAIT("待审核"), AUDITED("已审核"), SUCCESS("成功"), FAIL("失败")
     * @apiParam {String} payType <code>必须参数</code> 支付类型
     * @apiParam {String} beginDate <code>可选参数</code> 提交开始时间
     * @apiParam {String} endDate <code>可选参数</code> 提交结束时间
     * @apiSuccess {long} id ID
     * @apiSuccess {String} dateCreated 时间
     * @apiSuccess {String} seqNo 流水号
     * @apiSuccess {String} rechargeType 名称：RECHARGE_PRESENTED("充值赠送"), RECHARGE_COMMON("普通充值")
     * @apiSuccess {String} rechargeStatus <code>必选参数</code> 状态 ：WAIT("待审核"), SUCCESS("成功"), FAIL("失败")
     * @apiSuccess {BigDecimal} rechargeAmount 金额
     * @apiSuccess {String} payType 支付类型：ONLINE("线上支付"), OUTLINE("线下支付")
     * @apiSuccess {String} remark 说明
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "data":[
     *             {
     *                 "id":24,
     *                 "dateCreated":"2017-03-31 17:53:00",
     *                 "lastUpdated":"2017-03-31 17:53:00",
     *                 "seqNo":"201703311752571109992",
     *                 "merchantId":129,
     *                 "mallId":51,
     *                 "rechargeAmount":10.2,
     *                 "rechargeStatus":"SUCCESS",
     *                 "payType":"ONLINE",
     *                 "remark":"ONLINE",
     *                 "rechargeType":"RECHARGE_COMMON",
     *                 "operatorId":545
     *             }
     *             .....
     *         ],
     *         "totalCount":6,
     *         "totalPage":1,
     *         "pageNo":0,
     *         "pageSize":10,
     *         "url":"/merchant/recharge/page",
     *         "prevUrl":"/merchant/recharge/page?pageNo=0&pageSize=10",
     *         "nextUrl":"/merchant/recharge/page?pageNo=0&pageSize=10"
     *     }
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_RECHARGE_PAGE, method = RequestMethod.GET)
    public JsonResult page(MerchantRechargeFlowDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();

        RestDoing doing = jsonResult -> {
            if (null == dto) {
                jsonResult.errorParam("查询条件为空", log);
                return;
            }
            if (!EnumUtils.isValidEnum(MerchantRechargeStatus.class, dto.getRechargeStatus())) {
                jsonResult.errorParam("审核状态为空", log);
                return;
            }

            if (null == dto.getMallId()) {
                dto.setMallId(mallId);
            }

            if (null == dto.getMerchantId()) {
                dto.setMerchantId(userDto.merchant.getId());
            }

            PageResult<MerchantRechargeFlowDto> pageResult = merchantRechargeSrv.findRechargePage(dto, getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.setUrl(Routes.MERCHANT_RECHARGE_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /v1/merchant/recharge/save B 商家充值提交
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} rechargeAccount <code>必须参数</code> 汇款账号
     * @apiParam {String} bankName <code>必须参数</code> 开户行
     * @apiParam {String} rechargeAccountName <code>必须参数</code> 户名
     * @apiParam {BigDecimal} rechargeAmount <code>必须参数</code> 金额
     * @apiParam {String} rechargeDate <code>必须参数</code> 充值日期
     * @apiParam {String} rechargeVoucher <code>必须参数</code> 充值凭证
     * @apiSuccessExample {json} Success-Response:
     * {
     *      "code":"1",
     *      "desc":"成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_RECHARGE_SAVE, method = RequestMethod.POST)
    public JsonResult addInfo(@RequestBody MerchantRechargeFlow dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto == null) {
                jsonResult.remind("汇款信息为空",log);
                return;
            }
            if (StringUtils.isBlank(dto.getRechargeAccount())) {
                jsonResult.remind("汇款账号为空格",log);
                return;
            }
            if (dto.getRechargeAmount() == null) {
                jsonResult.remind("充值金额为空",log);
                return;
            }

            if (dto.getRechargeAmount().compareTo(BigDecimal.valueOf(0)) < 0) {
                jsonResult.remind("充值金额必须大于0元",log);
                return;
            }

            if(!BigDecimalUtils.isNumber(String.valueOf(dto.getRechargeAmount()))) {
                jsonResult.remind("充值金额最多两位小数", log);
                return;
            }

            if (StringUtils.isBlank(dto.getRechargeDate())) {
                jsonResult.remind("汇款日期为空",log);
                return;
            }
            if (StringUtils.isBlank(dto.getBankName())) {
                jsonResult.remind("开户行为空",log);
                return;
            }
            if (StringUtils.isBlank(dto.getRechargeAccountName())) {
                jsonResult.remind("户名为空",log);
                return;
            }
            if (StringUtils.isBlank(dto.getRechargeVoucher())) {
                jsonResult.remind("汇款凭证为空",log);
                return;
            }
            dto.setMerchantId(userDto.merchant.getId());
            dto.setMallId(userDto.mall.getId());
            dto.setRechargeStatus(MerchantRechargeStatus.WAIT);
            dto.setPayType(MerchantPayType.OUTLINE);
            dto.setRechargeType(MerchantRechargeType.RECHARGE_COMMON);
            dto.setOperatorId(userDto.getId());
            merchantRechargeFlowRepository.save(dto);

            //广播消息
            SysMessageHelper.SINGLETON.pushFinanceMsg(SysMessageConstants.M2M_MALL_MERCHANT_RECHARGE_SAVE_PENDING_AUDIT, null, userDto.mall.getId(),null);
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /v1/merchant/mall/recharge/save M 手动充值
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {BigDecimal} rechargeAmount <code>必须参数</code> 金额
     * @apiParam {String} rechargeType <code>必须参数</code> 充值类型：RECHARGE_PRESENTED("充值赠送"), RECHARGE_COMMON("普通充值")
     * @apiParam {String} merchantId <code>必须参数</code> 商户id
     * @apiParam {String} remark <code>必须参数</code> 备注
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code":"1",
     *  "desc":"成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_MALL_RECHARGE_SAVE, method = RequestMethod.POST)
    public JsonResult addMerchantRechargeFromMall(@RequestBody MerchantRechargeFlowDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto == null) {
                jsonResult.remind("充值信息为空",log);
                return;
            }
            Long merchantId = dto.getMerchantId();
            if (null == merchantId) {
                jsonResult.remind("商户id为空",log);
                return;
            }
            if (dto.getRechargeAmount() == null) {
                jsonResult.remind("充值金额为空",log);
                return;
            }

            if (dto.getRechargeAmount().compareTo(BigDecimal.valueOf(0)) < 0) {
                jsonResult.remind("充值金额必须大于0元",log);
                return;
            }

            if(!BigDecimalUtils.isNumber(String.valueOf(dto.getRechargeAmount()))) {
                jsonResult.remind("充值金额最多两位小数", log);
                return;
            }

            String rechargeType = dto.getRechargeType();
            if (StringUtils.isBlank(rechargeType)) {
                jsonResult.remind("充值类型为空",log);
                return;
            }

            String remark =dto.getRemark();
            if(StringUtils.isBlank(remark)){
                jsonResult.remind("备注为空",log);
                return;
            }

            if (!EnumUtils.isValidEnum(MerchantRechargeType.class, rechargeType) || MerchantRechargeType.ALL.toString().equals(rechargeType)) {
                jsonResult.remind("充值类型不正确",log);
                return;
            }

            Merchant merchant = merchantSrv.findOne(merchantId);
            if (null == merchant) {
                jsonResult.remind("商户不存在",log);
                return;
            }
            MerchantRechargeFlow merchantRechargeFlow = new MerchantRechargeFlow();
            merchantRechargeFlow.setMerchantId(merchantId);
            merchantRechargeFlow.setMallId(userDto.mall.getId());
            merchantRechargeFlow.setRechargeStatus(MerchantRechargeStatus.SUCCESS);
            merchantRechargeFlow.setPayType(MerchantPayType.RECHARGE_MALL);
            merchantRechargeFlow.setRemark(dto.getRemark());
            merchantRechargeFlow.setRechargeAmount(dto.getRechargeAmount());
            merchantRechargeFlow.setRechargeType(MerchantRechargeType.valueOf(rechargeType));
            merchantRechargeFlow.setOperatorId(userDto.getId());
            merchantRechargeFlow.setRemark(remark);
            merchantRechargeFlow = merchantRechargeFlowSrv.save(merchantRechargeFlow);
            Mall mall = mallSrv.findOne(merchantRechargeFlow.getMallId());
            String servicPhone = mall.getServiceTelephone();
            String content = SysMessageConstants.M2B_MERCHANT_MALL_RECHARGE_SAVE_SUCCESS.getContent();
            content = MessageFormat.format(content, DateUtils.formatDate(new Date()), merchantRechargeFlow.getRechargeAmount(), servicPhone);
            SysMessage message = SysMessageHelper.SINGLETON.createMsgBean(SysMessageConstants.M2B_MERCHANT_MALL_RECHARGE_SAVE_SUCCESS, SysMessageType.FINANCE, content);
            SysMessageHelper.SINGLETON.pushMsgByMallAndMerchantId(message, null, merchantId);
        };
        return doing.go(request, log);
    }

}
